﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.MODEL;
using KPIS.GERP.ESS.DAL;
using System.Linq;
using KPIS.DBM;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class ESS_ProjectOperation : System.Web.UI.Page
    {
        Main main = new Main();
        BGM_Project.BGM_Project pj = new BGM_Project.BGM_Project();
        BGM_ProjectExpense.BGM_ProjectExpense pjexp = new BGM_ProjectExpense.BGM_ProjectExpense();
        BGM_ProjectReport.BGM_ProjectReport pjrpt = new BGM_ProjectReport.BGM_ProjectReport();
        BGM_ProjectOperation.BGM_ProjectOperation po = new BGM_ProjectOperation.BGM_ProjectOperation();
        BGM_ProjectOperationExpense.BGM_ProjectOperationExpense poexp = new BGM_ProjectOperationExpense.BGM_ProjectOperationExpense();
        BGM_ProjectOperationExpenseRate.BGM_ProjectOperationExpenseRate poexprate = new BGM_ProjectOperationExpenseRate.BGM_ProjectOperationExpenseRate();
        BGM_ProjectOperationPerson.BGM_ProjectOperationPerson poper = new BGM_ProjectOperationPerson.BGM_ProjectOperationPerson();
        BGM_ProjectOperationReport.BGM_ProjectOperationReport porpt = new BGM_ProjectOperationReport.BGM_ProjectOperationReport();
        BGM_MAS_Option.BGM_MAS_Option op = new BGM_MAS_Option.BGM_MAS_Option();
        //FIM_Employees.FIM_Employees emp = new FIM_Employees.FIM_Employees();
        FIM_Employees.FIM_Employees emp = new FIM_Employees.FIM_Employees();
        FIM_MAS_ExpenseRates.FIM_MAS_ExpenseRates exprate = new FIM_MAS_ExpenseRates.FIM_MAS_ExpenseRates();
        //FIM_MAS_ExpenseRateTypes.FIM_MAS_ExpenseRateTypes rateType = new FIM_MAS_ExpenseRateTypes.FIM_MAS_ExpenseRateTypes();
        //FIM_MAS_ExpenseRateTypeGroups.FIM_MAS_ExpenseRateTypeGroups rateTypeGrp = new FIM_MAS_ExpenseRateTypeGroups.FIM_MAS_ExpenseRateTypeGroups();
        B_HrmEmployees emplist = new B_HrmEmployees();
        B_IcmMasResourceItem icmItem = new B_IcmMasResourceItem();
        ESS.BLL.B_MessageSend send = new ESS.BLL.B_MessageSend();
        ESS.BLL.B_MessageReply reply = new ESS.BLL.B_MessageReply();
        DBManager dbManager = new DBManager(DataProvider.SqlServer, KPIS.GERP.ESS.MODEL.SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            //this.cmdSendMessage1.Attributes.Add("onClick", string.Format("realPostBack(\"{0}\", \"\"); return false;", this.cmdSendMessage1.UniqueID));
            if (!IsPostBack)
            {
                // main code
                SetPagePermission();
                cmdProgress1_Click(null, null);
                SetProgress(null);

                // optional code
                LoadInfo();
                LoadDefault();
                LoadDDLProject();
                
                //LoadDDLEmpSeq();
                //LoadApprover();
            }
        }

        protected void cmdAddNew1_Click(object sender, EventArgs e)
        {
            if (liViewAll.Attributes["class"] == "Selected")
            {
                lblBgmProjOperSeq.Text = "";
                lblRecordStatus.Text = "W";
                SetProgress("");
                ClearControl1();
            }

            SetBody("PanelProgress1");
            SetControl("AddNew");
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            if (PanelProgress1.Visible)
            {
                Insert1();
            }
            //else if (PanelProgress2.Visible)
            //{
            //    Insert2();
            //}
            else if (PanelProgress3.Visible)
            {
                Insert3();
            }
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            if (PanelProgress1.Visible)
            {
                Update1();
            }
            //else if (PanelProgress2.Visible)
            //{
            //    Update2();
            //}
            else if (PanelProgress3.Visible)
            {
                Update3();
            }
        }

        protected void cmdEdit1_Click(object sender, EventArgs e)
        {
            GridDataItem item = GrdViewAll.Items[GrdViewAll.SelectedIndexes[0]];
            string strBgmProjOperSeq = main.WebString(item["bgm_proj_oper_seq"].Text);

            BGM_ProjectOperation.M_BGM_ProjectOperation info = po.GetInfo(strBgmProjOperSeq);
            lblBgmProjOperSeq.Text = info.bgm_proj_oper_seq.ToString();
            lblBgmProjOperCode.Text = info.bgm_proj_oper_code;
            lblBgmProjOperDate.Text = main.ConvertDBDateTimeToString(info.bgm_proj_oper_date, false);
            txtBgmYear.Text = info.bgm_year.ToString();
            LoadDDLProject();
            ddlBgmProjSeq.SelectedValue = info.bgm_proj_seq.ToString();
            dpStartDate.SetValue(info.start_date);
            dpEndDate.SetValue(info.end_date);
            txtBgmProjOperName.Text = info.bgm_proj_oper_name;
            txtAttendCount.Text = info.attend_count.ToString();
            lblRecordStatus.Text = info.record_status;
            lblFinRecordStatus.Text = info.record_status;
            lblFinRecordStatusName.Text = info.record_status_name;
            lblBgmProjName.Text = info.m_bgm_project.bgm_proj_name;

            lblBgmProjName2.Text = info.m_bgm_project.bgm_proj_name;
            LoadRepeaterPerson();

            LoadRepeater1();
            SetProgress(strBgmProjOperSeq);
            cmdSummary_Click(null, null);
            SetBody("PanelSummary");
            Session["ReportSeq"] = strBgmProjOperSeq;
        }

        protected void cmdCancel_Click(object sender, EventArgs e)
        {
            SetControl("AddNew");

            if (PanelProgress1.Visible)
            {
                ClearControl1();
                SetProgress(null);
            }
            else if (PanelProgress2.Visible)
            {
                ClearControl2();
            }
            else if (PanelProgress3.Visible)
            {
                ClearControl3();
            }
            else if (PanelSummary.Visible)
            {
                cmdViewAll_Click(null, null);
                SetProgress(null);
            }
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            if (PanelProgress1.Visible)
            {
                Delete1();
            }

            //if (PanelProgress2.Visible)
            //{
            //    Delete2();
            //}

            if (PanelProgress3.Visible)
            {
                Delete3();
            }

            if (PanelViewAll.Visible)
            {
                Delete1();
            }
        }

        //==================== main code area ========================
        protected void LoadGrdViewAll()
        {
            GrdViewAll.DataSource = po.GetFull(null, txtFilterBgmYear.Text, Session["WorkingJobSiteSeq"].ToString()
                , null, null, false, false);
            GrdViewAll.DataBind();
        }

        protected void SetPagePermission()
        {
            ViewState["Permission"] = "user-1";//main.GetPermission(Session["UserSeq"]);
        }

        protected void SetControl(string strCommand)
        {
            switch (strCommand)
            {
                case "ViewAll":
                    cmdAddNew1.Visible = true;
                    cmdEdit1.Visible = true;
                    cmdDelete1.Visible = true;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = false;
                    cmdCancel.Visible = false;
                    cmdSendMessage1.Visible = false;
                    cmdReport.Visible = false;

                    lblModeName.Text = "แสดงรายการ";
                    lblMode.Text = "V";
                    cmdCancelMessage.Visible = false;
                    //cmdViewAll_Click(null, null);
                    break;
                case "AddNew":
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;
                    cmdCancel.Visible = false;
                    cmdSendMessage1.Visible = false;
                    cmdReport.Visible = false;

                    lblModeName.Text = "เพิ่มรายการใหม่";
                    lblMode.Text = "A";
                    cmdCancelMessage.Visible = false;
                    //cmdProgress1_Click(null, null);
                    break;
                case "Edit":
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;
                    cmdCancel.Visible = true;
                    cmdSendMessage1.Visible = false;
                    cmdReport.Visible = false;

                    lblModeName.Text = "แก้ไขรายการ";
                    lblMode.Text = "E";
                    //cmdSummary_Click(null, null);
                    break;
                case "NoControl":
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = false;
                    cmdCancel.Visible = false;
                    cmdSendMessage1.Visible = false;
                    cmdReport.Visible = false;

                    lblModeName.Text = "แสดงรายการ";
                    lblMode.Text = "N";
                    cmdCancelMessage.Visible = false;
                    break;
            }
        }

        protected void SetBody(string strProGressID)
        {
            bool bSelected = false;
            List<Panel> PanelProgress = new List<Panel>();
            PanelProgress.Add(PanelProgress1);
            PanelProgress.Add(PanelProgress2);
            PanelProgress.Add(PanelProgress3);
            PanelProgress.Add(PanelSummary);
            PanelProgress.Add(PanelViewAll);

            List<HtmlGenericControl> liProgress = new List<HtmlGenericControl>();
            liProgress.Add(li1);
            liProgress.Add(li2);
            liProgress.Add(li3);
            liProgress.Add(liSummary);
            liProgress.Add(liViewAll);

            for (int i = 0; i < PanelProgress.Count; i++)
            {
                bSelected = (PanelProgress[i].ID == strProGressID);
                PanelProgress[i].Visible = bSelected;
                liProgress[i].Attributes["class"] = (bSelected ? "Selected" : "");
            }
        }

        protected void SetProgress(string strPK)
        {
            if (string.IsNullOrEmpty(strPK))
            {
                imgComplete1.Visible = false;
                imgInComplete1.Visible = true;
                cmdProgress1.Enabled = true;

                imgComplete2.Visible = false;
                imgInComplete2.Visible = true;
                cmdProgress2.Enabled = false;

                imgComplete3.Visible = false;
                imgInComplete3.Visible = true;
                cmdProgress3.Enabled = false;

                cmdSummary.Enabled = false;
                cmdCancelMessage.Visible = false;
            }
            else
            {
                int nCount = 0;
                imgComplete1.Visible = true;
                imgInComplete1.Visible = false;

                nCount = ((IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense>)poexp.GetList(strPK, null, null)).Count;

                imgComplete2.Visible = nCount > 0;
                imgInComplete2.Visible = nCount == 0;
                cmdProgress2.Enabled = true;

                nCount = ((IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson>)poper.GetList(strPK)).Count;

                imgComplete3.Visible = nCount > 0;
                imgInComplete3.Visible = nCount == 0;
                cmdProgress3.Enabled = true;
                cmdSummary.Enabled = true;

                string strRecordStatus = po.GetInfo(strPK).record_status;
                bool bCanEdit = (strRecordStatus == "W" || strRecordStatus == "R");
                cmdProgress1.Enabled = bCanEdit;
                cmdProgress2.Enabled = bCanEdit;
                //cmdProgress3.Enabled = bCanEdit;

                string strMessageStatus = send.GetInfoFromRefSeq(strPK, "bgm_project_operation").message_status;
                cmdCancelMessage.Visible = strMessageStatus == "0";
            }
        }

        protected void ClearControl1()
        {
            lblBgmProjOperSeq.Text = "";
            lblBgmProjOperCode.Text = "";
            lblBgmProjOperDate.Text = DateTime.Today.ToShortDateString();
            ddlBgmProjSeq.SelectedIndex = 0;
            txtBgmProjOperName.Text = "";
            txtAttendCount.Text = "";
            dpStartDate.SetValue("");
            dpEndDate.SetValue("");
            ddlBgmProjSeq.Enabled = true;
        }

        protected void ClearControl2()
        {
            txtAmount.Text = "";
            ViewState["Amount"] = 0;
        }

        protected void ClearControl3()
        {
            ddlEmpSeq.SelectedIndex = -1;
            ddlEmpSeq.Text = "";
            lblPerPosName.Text = "";
            lblPerJobsiteName.Text = "";
            lblPerClassName.Text = "";
        }

        //==================== optional code area =======================
        protected void LoadDDLProject()
        {
            ddlBgmProjSeq.DataSource = pj.GetList(txtBgmYear.Text, lblWorkingJobSiteSeq.Text, null);//Session["UserInternalJobsiteSeq"].ToString()
            ddlBgmProjSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlBgmProjSeq);
            ddlBgmProjSeq.SelectedIndex = 0;
        }

        protected void LoadInfo()
        { 
            if(Session["WorkingJobSiteSeq"] == null || Session["WorkingJobSiteName"] == null)
            {
                Response.Redirect(@"~/App_UI/Forms/Default.aspx");
            }
            lblWorkingJobSiteSeq.Text =  Session["WorkingJobSiteSeq"].ToString(); 
            lblWorkingJobSiteName.Text = Session["WorkingJobSiteName"].ToString();
        }

        protected void LoadDefault()
        {
            int year = main.GetSystemControls().default_bgm_year.Value;
            txtBgmYear.Text = year.ToString();
            txtBgmYear.MinValue = year;
            txtBgmYear.MaxValue = year + 1;

            txtFilterBgmYear.Text = year.ToString();
            txtFilterBgmYear.MinValue = year - 20;
            txtFilterBgmYear.MaxValue = year + 1;

            lblBgmProjOperDate.Text = DateTime.Today.ToShortDateString();
        }

        protected void LoadGrdBgmProjectOperationExpense()
        {
            grdBgmProjectOperationExpense.DataSource = poexp.GetProjectExpense(lblBgmProjOperSeq.Text
                , ddlBgmProjSeq.SelectedValue); //ViewState["ProjectExpInfo"];

            GridGroupByExpression group1 = new GridGroupByExpression(grdBgmProjectOperationExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name"));
            GridGroupByExpression group2 = new GridGroupByExpression(grdBgmProjectOperationExpense.Columns.FindByUniqueName("m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name"));

            grdBgmProjectOperationExpense.MasterTableView.GroupByExpressions.Add(group1);
            grdBgmProjectOperationExpense.MasterTableView.GroupByExpressions.Add(group2);
            grdBgmProjectOperationExpense.DataBind();
        }

        protected void LoadFinData()
        {
            string strBgmProjOperSeq = lblBgmProjOperSeq.Text;
            BGM_Project.M_BGM_Project projInfo = new BGM_Project.M_BGM_Project();
            projInfo = pj.GetInfo(ddlBgmProjSeq.SelectedValue);

            BGM_ProjectOperation.M_BGM_ProjectOperation operInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
            operInfo = po.GetInfo(strBgmProjOperSeq);

            lblFinBgmSubActName.Text = main.FinString(projInfo.m_bgm_subactivity.bgm_strat_list_name);
            lblFinBgmActName.Text = main.FinString(projInfo.m_bgm_activity.bgm_strat_list_name);
            lblFinBgmOutputName.Text = main.FinString(projInfo.m_bgm_output.bgm_strat_list_name);
            lblFinBgmProjName.Text = main.FinString(projInfo.bgm_proj_name);

            lblFinAttendCount.Text = main.FinString(txtAttendCount.Text);
            lblFinBgmProjOperDate.Text = main.FinString(lblBgmProjOperDate.Text);
            lblFinBgmProjOperName.Text = main.FinString(txtBgmProjOperName.Text);
            lblFinBgmProjOperCode.Text = main.FinString(lblBgmProjOperCode.Text);
            lblFinBgmYear.Text = main.FinString(txtBgmYear.Text);
            lblFinEndDate.Text = main.FinString(dpEndDate.GetStringValue());
            lblFinStartDate.Text = main.FinString(dpStartDate.GetStringValue());
            lblRecordStatus.Text = main.FinString(operInfo.record_status);
            lblSendBackRemark.Text = "";
            tableSendBackRemark.Visible = false;

            switch (lblRecordStatus.Text)
            {
                case "W" :
                    lblFinRecordStatusName.Text = "ดำเนินการอยู่";
                    lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                    cmdSendMessage1.Visible = true;
                    break;
                case "P" :
                    lblFinRecordStatusName.Text = "รอการอนุมัติโดย " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                    lblFinRecordStatusName.ForeColor = System.Drawing.Color.Blue;
                    cmdSendMessage1.Visible = false;
                    break;
                case "A" :
                    lblFinRecordStatusName.Text = "อนุมัติโดย " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                    lblFinRecordStatusName.ForeColor = System.Drawing.Color.Green;
                    cmdSendMessage1.Visible = false;
                    break;
                case "R" :
                    lblFinRecordStatusName.Text = "ตีกลับ " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                    lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                    cmdSendMessage1.Visible = true;
                    tableSendBackRemark.Visible = true;

                    var replys = reply.GetInfoFromRefSeq(strBgmProjOperSeq, "bgm_project_operation");

                    if (replys.Count > 0)
                    {
                        lblSendBackRemark.Text = replys[0].remarks;
                    }

                    //lblSendBackRemark.Text = reply.GetInfoFromRefSeq(strBgmProjOperSeq, "bgm_project_operation")[0].remarks;
                    break;
                default :
                    lblFinRecordStatusName.Text = "รอการยืนยัน " + send.GetLatestMessageStatus(strBgmProjOperSeq, "bgm_project_operation").to_user_name;
                    lblFinRecordStatusName.ForeColor = System.Drawing.Color.Red;
                    cmdSendMessage1.Visible = true;
                    break;
            }

            LoadFinProjectExpense(strBgmProjOperSeq, ddlBgmProjSeq.SelectedValue);

            IList<BGM_MAS_Option.M_BGM_MAS_Option> optionInfoList = op.GetListFromBgmProjSeq("3", ddlBgmProjSeq.SelectedValue);// HardCode
            Repeater2.DataSource = optionInfoList;
            Repeater2.DataBind();

            IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> personInfoList = poper.GetFull(strBgmProjOperSeq);
            Repeater3.DataSource = personInfoList;
            Repeater3.DataBind();

            cmdReport.Visible = true;
        }

        protected void LoadFinProjectExpense(string strBgmProjOperSeq, string strBgmProjSeq)
        {
            //double dSumAmount = 0;
            //double dSumAmount1 = 0;
            //double dSumAmount2 = 0;
            //double dSumAmountGrp = 0;
            //double dSumAmountSource = 0;
            //int nOldBgmExpSeq1 = 0;
            //int nOldBgmExpSeq2 = 0;
            //int nOldBgmExpGrpSeq = 0;
            //int nOldBgmSourceSeq = 0;
            IList<BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense> masterListInfo
                = poexp.GetProjectExpense(strBgmProjOperSeq, strBgmProjSeq).Where(m => (m.amount ?? 0) > 0).ToList();

            #region old
            //DataTable dtbSource = new DataTable();
            //dtbSource.Columns.Add("bgm_source_seq", typeof(Int32));
            //dtbSource.Columns.Add("bgm_source_name", typeof(String));
            //dtbSource.Columns.Add("amount", typeof(Double));

            //DataTable dtbExpGrp = new DataTable();
            //dtbExpGrp.Columns.Add("bgm_source_seq", typeof(Int32));
            //dtbExpGrp.Columns.Add("bgm_exp_grp_seq", typeof(Int32));
            //dtbExpGrp.Columns.Add("bgm_exp_grp_name", typeof(String));
            //dtbExpGrp.Columns.Add("amount", typeof(Double));

            //DataTable dtbExp2 = new DataTable();
            //dtbExp2.Columns.Add("bgm_source_seq", typeof(Int32));
            //dtbExp2.Columns.Add("bgm_exp_grp_seq", typeof(Int32));
            //dtbExp2.Columns.Add("bgm_exp_seq", typeof(Int32));
            //dtbExp2.Columns.Add("bgm_exp_name", typeof(String));
            //dtbExp2.Columns.Add("amount", typeof(Double));

            //DataTable dtbExp1 = new DataTable();
            //dtbExp1.Columns.Add("bgm_source_seq", typeof(Int32));
            //dtbExp1.Columns.Add("upper_bgm_exp_seq", typeof(Int32));
            //dtbExp1.Columns.Add("bgm_exp_seq", typeof(Int32));
            //dtbExp1.Columns.Add("bgm_exp_name", typeof(String));
            //dtbExp1.Columns.Add("amount", typeof(Double));

            //DataTable dtbExp = new DataTable();
            //dtbExp.Columns.Add("bgm_source_seq", typeof(Int32));
            //dtbExp.Columns.Add("upper_bgm_exp_seq", typeof(Int32));
            //dtbExp.Columns.Add("bgm_exp_seq", typeof(Int32));
            //dtbExp.Columns.Add("bgm_exp_name", typeof(String));
            //dtbExp.Columns.Add("descr", typeof(String));
            //dtbExp.Columns.Add("amount", typeof(Double));

            //for (int i = 0; i < masterListInfo.Count; i++)
            //{
            //    BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense info = masterListInfo[i];
            //    DataRow dr = dtbExp.NewRow();
            //    double dAmount = (info.amount == null ? 0 : info.amount.Value);

            //    if (dAmount > 0)
            //    {
            //        dr["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
            //        dr["upper_bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq;
            //        dr["bgm_exp_seq"] = info.m_bgm_projectexpense.bgm_exp_seq;
            //        dr["bgm_exp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name;
            //        dr["descr"] = info.bgm_proj_oper_exp_descr;
            //        dr["amount"] = dAmount;
            //        dtbExp.Rows.Add(dr);
            //        dSumAmount += dAmount;
            //        // exp1 ======================================================================================
            //        if (info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq == nOldBgmExpSeq1
            //             && info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
            //        {
            //            dSumAmount1 += dAmount;
            //        }
            //        else
            //        {
            //            DataRow dr1 = dtbExp1.NewRow();
            //            dr1["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
            //            dr1["upper_bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq;
            //            dr1["bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq;
            //            dr1["bgm_exp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.bgm_exp_name;

            //            if (dtbExp1.Rows.Count > 0)
            //            {
            //                dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount"] = dSumAmount1;
            //            }

            //            dSumAmount1 = dAmount;
            //            nOldBgmExpSeq1 = info.m_bgm_projectexpense.m_bgm_mas_expense.upper_bgm_exp_seq.Value;

            //            dtbExp1.Rows.Add(dr1);
            //        }
            //        // exp2 ======================================================================================
            //        if (info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq == nOldBgmExpSeq2
            //             && info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
            //        {
            //            dSumAmount2 += dAmount;
            //        }
            //        else
            //        {
            //            DataRow dr2 = dtbExp2.NewRow();
            //            dr2["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
            //            dr2["bgm_exp_grp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq;
            //            dr2["bgm_exp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq;
            //            dr2["bgm_exp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.m_bgm_mas_expense_upper.bgm_exp_name;

            //            if (dtbExp2.Rows.Count > 0)
            //            {
            //                dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount"] = dSumAmount2;
            //            }

            //            dSumAmount2 = dAmount;
            //            nOldBgmExpSeq2 = info.m_bgm_projectexpense.m_bgm_mas_expense.m_bgm_mas_expense_upper.upper_bgm_exp_seq.Value;

            //            dtbExp2.Rows.Add(dr2);
            //        }
            //        // grp ======================================================================================
            //        if (info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq == nOldBgmExpGrpSeq
            //            && info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
            //        {
            //            dSumAmountGrp += dAmount;
            //        }
            //        else
            //        {
            //            DataRow drGrp = dtbExpGrp.NewRow();
            //            drGrp["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
            //            drGrp["bgm_exp_grp_seq"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq;
            //            drGrp["bgm_exp_grp_name"] = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_name;

            //            if (dtbExpGrp.Rows.Count > 0)
            //            {
            //                dtbExpGrp.Rows[dtbExpGrp.Rows.Count - 1]["amount"] = dSumAmountGrp;
            //            }

            //            dSumAmountGrp = dAmount;
            //            nOldBgmExpGrpSeq = info.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq.Value;

            //            dtbExpGrp.Rows.Add(drGrp);
            //        }
            //        // source ======================================================================================
            //        if (info.m_bgm_projectexpense.bgm_source_seq == nOldBgmSourceSeq)
            //        {
            //            dSumAmountSource += dAmount;
            //        }
            //        else
            //        {
            //            DataRow drSource = dtbSource.NewRow();
            //            drSource["bgm_source_seq"] = info.m_bgm_projectexpense.bgm_source_seq;
            //            drSource["bgm_source_name"] = info.m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name;

            //            if (dtbSource.Rows.Count > 0)
            //            {
            //                dtbSource.Rows[dtbSource.Rows.Count - 1]["amount"] = dSumAmountSource;
            //            }

            //            dSumAmountSource = dAmount;
            //            nOldBgmSourceSeq = info.m_bgm_projectexpense.bgm_source_seq.Value;

            //            dtbSource.Rows.Add(drSource);
            //        }
            //    }

            //    if (i == masterListInfo.Count - 1 && dtbSource.Rows.Count > 0)
            //    {
            //        dtbSource.Rows[dtbSource.Rows.Count - 1]["amount"] = dSumAmountSource;
            //        dtbExpGrp.Rows[dtbExpGrp.Rows.Count - 1]["amount"] = dSumAmountGrp;
            //        dtbExp2.Rows[dtbExp2.Rows.Count - 1]["amount"] = dSumAmount2;
            //        dtbExp1.Rows[dtbExp1.Rows.Count - 1]["amount"] = dSumAmount1;
            //    }
            //}
            #endregion

            RepeaterBgmSource.DataSource = masterListInfo
                .GroupBy(m => new { m.m_bgm_projectexpense.bgm_source_seq, m.m_bgm_projectexpense.m_bgm_mas_source.bgm_source_name })
                .Select(m => new { bgm_source_seq = m.Key.bgm_source_seq, bgm_source_name = m.Key.bgm_source_name, amount = m.Sum(s => s.amount) });
            RepeaterBgmSource.DataBind();

            foreach (RepeaterItem item in RepeaterBgmSource.Items)
            {
                Repeater RepeaterBgmExp = (Repeater)item.FindControl("RepeaterBgmExp");
                Label lblBgmSourceSeq = (Label)item.FindControl("lblBgmSourceSeq");

                RepeaterBgmExp.DataSource = masterListInfo.Where(m => m.m_bgm_projectexpense.bgm_source_seq == main.ConvertNullInt(lblBgmSourceSeq.Text));
                RepeaterBgmExp.DataBind();

                #region old
                //Repeater RepeaterBgmExpGrp = (Repeater)RepeaterBgmSource.Items[i].FindControl("RepeaterBgmExpGrp");
                //Label lblBgmSourceSeq = (Label)RepeaterBgmSource.Items[i].FindControl("lblBgmSourceSeq");

                //DataTable dtbExpGrpCopy = dtbExpGrp.Copy();
                //dtbExpGrpCopy.Rows.Clear();
                //DataRow[] drc = dtbExpGrp.Select("bgm_source_seq = " + lblBgmSourceSeq.Text);
                //foreach (DataRow dr in drc)
                //{
                //    DataRow drCopy = dr;
                //    dtbExpGrpCopy.ImportRow(drCopy);
                //}

                //RepeaterBgmExpGrp.DataSource = dtbExpGrpCopy;
                //RepeaterBgmExpGrp.DataBind();

                //for (int j = 0; j < RepeaterBgmExpGrp.Items.Count; j++)
                //{
                //    Repeater RepeaterBgmExp2 = (Repeater)RepeaterBgmExpGrp.Items[j].FindControl("RepeaterBgmExp2");
                //    Label lblBgmExpGrpSeq = (Label)RepeaterBgmExpGrp.Items[j].FindControl("lblBgmExpGrpSeq");

                //    DataTable dtbExp2Copy = dtbExp2.Copy();
                //    dtbExp2Copy.Rows.Clear();
                //    DataRow[] drc2 = dtbExp2.Select("bgm_source_seq = " + lblBgmSourceSeq.Text
                //        + " and bgm_exp_grp_seq = " + lblBgmExpGrpSeq.Text);
                //    foreach (DataRow dr in drc2)
                //    {
                //        DataRow drCopy = dr;
                //        dtbExp2Copy.ImportRow(drCopy);
                //    }

                //    RepeaterBgmExp2.DataSource = dtbExp2Copy;
                //    RepeaterBgmExp2.DataBind();

                //    for (int k = 0; k < RepeaterBgmExp2.Items.Count; k++)
                //    {
                //        Repeater RepeaterBgmExp1 = (Repeater)RepeaterBgmExp2.Items[k].FindControl("RepeaterBgmExp1");
                //        Label lblBgmExpSeq = (Label)RepeaterBgmExp2.Items[k].FindControl("lblBgmExpSeq");

                //        DataTable dtbExp1Copy = dtbExp1.Copy();
                //        dtbExp1Copy.Rows.Clear();
                //        DataRow[] drc3 = dtbExp1.Select("bgm_source_seq = " + lblBgmSourceSeq.Text
                //            + " and upper_bgm_exp_seq = " + lblBgmExpSeq.Text);
                //        foreach (DataRow dr in drc3)
                //        {
                //            DataRow drCopy = dr;
                //            dtbExp1Copy.ImportRow(drCopy);
                //        }

                //        RepeaterBgmExp1.DataSource = dtbExp1Copy;
                //        RepeaterBgmExp1.DataBind();

                //        for (int m = 0; m < RepeaterBgmExp1.Items.Count; m++)
                //        {
                //            Repeater RepeaterBgmExp = (Repeater)RepeaterBgmExp1.Items[m].FindControl("RepeaterBgmExp");
                //            Label lblBgmExpSeq2 = (Label)RepeaterBgmExp1.Items[m].FindControl("lblBgmExpSeq");

                //            DataTable dtbExpCopy = dtbExp.Copy();
                //            dtbExpCopy.Rows.Clear();
                //            DataRow[] drc4 = dtbExp.Select("bgm_source_seq = " + lblBgmSourceSeq.Text
                //                + " and upper_bgm_exp_seq = " + lblBgmExpSeq2.Text);
                //            foreach (DataRow dr in drc4)
                //            {
                //                DataRow drCopy = dr;
                //                dtbExpCopy.ImportRow(drCopy);
                //            }

                //            RepeaterBgmExp.DataSource = dtbExpCopy;
                //            RepeaterBgmExp.DataBind();
                //        }
                //    }
                //}
                #endregion
            }

            lblFinSumAmount.Text = (masterListInfo.Sum(m => m.amount) ?? 0).ToString("#,##0.00");
        }

        protected void cmdProgress1_Click(object sender, EventArgs e)
        {
            SetBody("PanelProgress1");

            if (imgInComplete1.Visible)
            {
                ddlBgmProjSeq.Enabled = true;
                SetControl("AddNew");
                lblRecordStatus.Text = "W";
                lblFinRecordStatus.Text = "W";
                lblFinRecordStatusName.Text = "รอการยืนยัน";
            }
            else
            {
                ddlBgmProjSeq.Enabled = false;
                SetControl("Edit");
            }
        }

        protected void cmdProgress2_Click(object sender, EventArgs e)
        {
            LoadRepeater4();
            LoadGrdBgmProjectOperationExpense();
            SetBody("PanelProgress2");
            SetControl("NoControl");
        }

        protected void cmdProgress3_Click(object sender, EventArgs e)
        {
            LoadRepeaterPerson();
            SetBody("PanelProgress3");
            SetControl("AddNew");
        }

        protected void cmdSummary_Click(object sender, EventArgs e)
        {
            SetBody("PanelSummary");
            SetControl("NoControl");
            LoadFinData();
            PanelMessageSend.Visible = false;
        }

        protected void cmdViewAll_Click(object sender, EventArgs e)
        {
            LoadGrdViewAll();
            SetBody("PanelViewAll");
            SetControl("ViewAll");
        }

        protected void cmdCloseExpenseSummary_Click(object sender, ImageClickEventArgs e)
        {
            PanelExpenseSummary.Visible = false;
        }

        protected void cmdOpenExpenseSummary_Click(object sender, EventArgs e)
        {
            PanelExpenseSummary.Visible = true;
        }

        protected void ddlBgmProjSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRepeater1();
            string strBgmProjName = ddlBgmProjSeq.Text;

            if (ddlBgmProjSeq.SelectedIndex > 0)
            {
                txtBgmProjOperName.Text = strBgmProjName;
                lblBgmProjName.Text = strBgmProjName;
                lblBgmProjName2.Text = strBgmProjName;
            }
            else
            {
                txtBgmProjOperName.Text = "";
                lblBgmProjName.Text = "";
                lblBgmProjName2.Text = "";
            }
        }

        protected void grdBgmProjectOperationExpense_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "AddExpense")
            {
                GridDataItem item = (GridDataItem)e.Item;
                lblBgmProjOperExpSeq.Text = main.WebString(item["bgm_proj_oper_exp_seq"].Text);
                lblBgmProjExpSeq.Text = main.WebString(item["bgm_proj_exp_seq"].Text);
                lblBgmExpName.Text = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name"].Text);
                lblRemainAmount.Text = main.WebString(item["m_bgm_projectexpense.amount"].Text);
                lblBgmExpSeq.Text = main.WebString(item["m_bgm_projectexpense.bgm_exp_seq"].Text);
                lblBgmSourceSeq.Text = main.WebString(item["m_bgm_projectexpense.bgm_source_seq"].Text);
                lblBgmExpGrpSeq.Text = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text);

                if (lblBgmProjOperExpSeq.Text.Length > 0)
                {
                    txtBgmProjOperExpDescr.Text = main.WebString(item["bgm_proj_oper_exp_descr"].Text);
                }
                else
                {
                    txtBgmProjOperExpDescr.Text = main.WebString(item["m_bgm_projectexpense.descr"].Text);
                }
                
                txtAmount.Text = main.WebString(item["amount"].Text);
                ViewState["Amount"] = main.ConvertNullDouble(txtAmount.Text);
                string strBgmExpGrpSeq = main.WebString(item["m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text);
                int nExpRateCount = Convert.ToInt32(item["exp_rate_count"].Text);

                if (strBgmExpGrpSeq == "3")
                {
                    lblIcmResItemSeq.Text = main.WebString(item["m_bgm_projectexpense.icm_res_item_seq"].Text);

                    DataRow dr = icmItem.GetInfo(lblIcmResItemSeq.Text);

                    lblIcmResItemCode.Text = dr["icm_res_item_code"].ToString();
                    lblIcmResItemName.Text = dr["icm_res_item_name"].ToString();

                    if (lblBgmProjOperExpSeq.Text.Length == 0)
                    {
                        txtUnitPriceProj.Text = main.WebString(item["m_bgm_projectexpense.unit_price"].Text);
                        txtUnitQtyProj.Text = main.WebString(item["m_bgm_projectexpense.unit_qty"].Text);
                        txtAmount.Text = main.WebString(item["m_bgm_projectexpense.amount"].Text);
                    }
                    else
                    {
                        txtUnitPriceProj.Text = main.WebString(item["unit_price"].Text);
                        txtUnitQtyProj.Text = main.WebString(item["unit_qty"].Text);
                        txtAmount.Text = main.WebString(item["amount"].Text);
                    }

                    PanelInv.Visible = true;
                    PanelExpRate.Visible = false;

                    txtAmount.Enabled = false;
                }
                else if (nExpRateCount > 0)
                {
                    PanelInv.Visible = false;
                    //SetQty(lblBgmExpSeq.Text);
                    PanelExpRate.Visible = true;
                    //LoadRepeaterFilter();
                    LoadRepeaterExpRate();

                    txtAmount.Enabled = false;
                }
                else
                {
                    PanelInv.Visible = false;
                    PanelExpRate.Visible = false;
                    txtAmount.Enabled = true;
                }

                bool bAddNew = (lblBgmProjOperExpSeq.Text.Length == 0);
                cmdInsert2.Visible = bAddNew;
                cmdUpdate2.Visible = !bAddNew;
                PanelProjOperExp.Visible = true;
            }

            PanelOpacity.Visible = true;
        }

        //protected void SetQty(string strBgmExpSeq)
        //{
        //    ViewState["bRelate"] = rateType.GetRelate(strBgmExpSeq);
        //}

        //public void LoadDDLEmpSeq(RadComboBoxItemsRequestedEventArgs e)
        //{
        //    string strFilter = e.Text;
        //    DataTable dtb = emplist.GetBgmProjOperPerList(lblBgmProjOperSeq.Text, strFilter).Tables[0];
        //    int nCount = dtb.Rows.Count;

        //    if (nCount > 0)
        //    {
        //        int itemOffset = e.NumberOfItems;
        //        int endOffset = Math.Min(itemOffset + 10, nCount);
        //        e.EndOfItems = endOffset == nCount;

        //        for (int i = itemOffset; i < endOffset; i++)
        //        {
        //            ddlEmpSeq.Items.Add(new RadComboBoxItem(dtb.Rows[i]["emp_name"].ToString(), dtb.Rows[i]["emp_seq"].ToString()));
        //        }

        //        e.Message = main.GetStatusMessage(endOffset, nCount);
        //    }
        //}

        protected void ddlEmpSeq_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strEmpSeq = ddlEmpSeq.SelectedValue;

            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));
                lblPerPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblPerJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
                lblPerClassName.Text = dtb.Rows[0]["class_name"].ToString();
                ddlEmpSeq.Text = dtb.Rows[0]["full_name"].ToString();
            }
        }

        protected void RepeaterPerson_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string strCommandName = e.CommandName;

            if (strCommandName == "edit")
            {
                RepeaterItem item = e.Item;
                lblBgmProjOperPerSeq.Text = main.WebString(((Label)item.FindControl("lblRepeaterBgmProjOperPerSeq")).Text);
                ddlEmpSeq.SelectedValue = main.WebString(((Label)item.FindControl("lblRepeaterEmpSeq")).Text);
                ddlEmpSeq.Text = main.WebString(((LinkButton)item.FindControl("cmdRepeaterEdit")).Text);

                ddlEmpSeq_SelectedIndexChanged(null, null);
                SetControl("Edit");
                cmdDelete1.Visible = true;
            }
        }

        //protected void LoadRepeaterFilter()
        //{
        //    string strBgmExpSeq = lblBgmExpSeq.Text;

        //    RepeaterFilter.DataSource = rateTypeGrp.GetFull(strBgmExpSeq);
        //    RepeaterFilter.DataBind();
        //}

        //protected void RepeaterFilter_ItemDataBound(object sender, RepeaterItemEventArgs e)
        //{
        //    if (e.Item is RepeaterItem)
        //    {
        //        if (e.Item.ItemType != ListItemType.Header)
        //        {
        //            RepeaterItem dataItem = (RepeaterItem)e.Item;
        //            Label lbl = (Label)dataItem.FindControl("lblExpRateTypeGrpSeq");
        //            //Label lbl2 = (Label)dataItem.FindControl("lblExpRateMapSeq");
        //            RadComboBox ddl = (RadComboBox)dataItem.FindControl("ddlExpRateTypeSeq");

        //            ddl.DataSource = rateType.GetList(lbl.Text);
        //            ddl.DataBind();

        //            main.InsertEmptyDDLAll(ddl);
        //            ddl.SelectedIndex = 0;
        //        }
        //    }
        //}

        protected void LoadRepeaterExpRate()
        {
            string strBgmProjOperExpSeq = lblBgmProjOperExpSeq.Text;
            string strBgmProjExpSeq = lblBgmProjExpSeq.Text;
            //string strBgmSourceSeq = lblBgmSourceSeq.Text;
            //string strSeq;
            //string[] strExpRateTypeSeq = new string[RepeaterFilter.Items.Count];
            //int j = 0;

            //for (int i = 0; i < strExpRateTypeSeq.Length; i++)
            //{
            //    RadComboBox ddl = (RadComboBox)RepeaterFilter.Items[i].FindControl("ddlExpRateTypeSeq");
            //    strSeq = ddl.SelectedValue;

            //    if (strSeq.Length > 0)
            //    {
            //        strExpRateTypeSeq[j] = strSeq;
            //        j++;
            //    }
            //}

            if (strBgmProjOperExpSeq.Length > 0)
            {
                RepeaterExpRate.DataSource = poexprate.GetFull(strBgmProjOperExpSeq, null);
            }
            else
            {
                RepeaterExpRate.DataSource = poexprate.GetFull2(strBgmProjExpSeq, null);
            }

            RepeaterExpRate.DataBind();
        }

        protected void RepeaterExpRate_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item is RepeaterItem)
            {
                if (e.Item.ItemType != ListItemType.Header)
                {
                    RepeaterItem dataItem = e.Item;
                    RadNumericTextBox txtMan = (RadNumericTextBox)dataItem.FindControl("txtMan");
                    RadNumericTextBox txtDay = (RadNumericTextBox)dataItem.FindControl("txtDay");
                    RadNumericTextBox txtHour = (RadNumericTextBox)dataItem.FindControl("txtHour");
                    RadNumericTextBox txtMinute = (RadNumericTextBox)dataItem.FindControl("txtMinute");
                    Label lblExpRateName = (Label)dataItem.FindControl("lblExpRateName");
                    Label lblExpRateDescr = (Label)dataItem.FindControl("lblExpRateDescr");
                    Label lblMan = (Label)dataItem.FindControl("lblMan");
                    Label lblDay = (Label)dataItem.FindControl("lblDay");
                    Label lblHour = (Label)dataItem.FindControl("lblHour");
                    Label lblMinute = (Label)dataItem.FindControl("lblMinute");
                    Label lblRelateMan = (Label)dataItem.FindControl("lblRelateMan");
                    Label lblRelateDay = (Label)dataItem.FindControl("lblRelateDay");

                    bool bRelateMan = lblRelateMan.Text.ToLower() == "true";
                    bool bRelateDay = lblRelateDay.Text.ToLower() == "true";

                    lblExpRateName.ToolTip = lblExpRateDescr.Text;

                    if (bRelateMan)
                    {
                        txtMan.Visible = true;
                        lblMan.Visible = true;
                    }

                    if (bRelateDay)
                    {
                        txtDay.Visible = true;
                        lblDay.Visible = true;
                    }

                    //if (bRelate[2])
                    //{
                    //    txtHour.Visible = true;
                    //    lblHour.Visible = true;
                    //}

                    //if (bRelate[3])
                    //{
                    //    txtMinute.Visible = true;
                    //    lblMinute.Visible = true;
                    //}
                }
            }
        }

        protected void cmdAmountMax_Click(object sender, EventArgs e)
        {
            RepeaterItem item = (RepeaterItem)((LinkButton)sender).Parent;

            ((RadNumericTextBox)item.FindControl("txtAmount")).Text = ((HtmlInputHidden)item.FindControl("hAmountMax")).Value;
            CalculateTotalAmount(sender);
        }

        protected void ddlExpRateTypeSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRepeaterExpRate();
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            LoadDDLProject();
        }

        protected void txtFilterBgmYear_TextChanged(object sender, EventArgs e)
        {
            LoadGrdViewAll();
        }

        protected void txtAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtMan_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtDay_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtHour_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtMinute_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void CalculateTotalAmount(object sender)
        {
            RepeaterItem item = null;

            if (sender.GetType().Name == "RadNumericTextBox")
            {
                item = (RepeaterItem)((RadNumericTextBox)sender).Parent;
            }
            else if (sender.GetType().Name == "LinkButton")
            {
                item = (RepeaterItem)((LinkButton)sender).Parent;
            }

            HtmlInputHidden hAmountMin = (HtmlInputHidden)item.FindControl("hAmountMin");
            HtmlInputHidden hAmountMax = (HtmlInputHidden)item.FindControl("hAmountMax");
            RadNumericTextBox txtAmount = (RadNumericTextBox)item.FindControl("txtAmount");
            double dAmount = (txtAmount.Value != null ? txtAmount.Value.Value : 1);
            double dMin = (main.WebString(hAmountMin.Value) != "" ? Convert.ToDouble(hAmountMin.Value) : 0);
            double dMax = (main.WebString(hAmountMax.Value) != "" ? Convert.ToDouble(hAmountMax.Value) : 0);

            if (dAmount > dMax)
            {
                txtAmount.Text = dMax.ToString("#,###.00");
                main.MessageAlert(Page, "จำนวนเงินมากกว่าอัตราค่าใช้จ่าย");
                return;
            }

            if (dAmount < dMin)
            {
                txtAmount.Text = dMin.ToString("#,###.00");
                main.MessageAlert(Page, "จำนวนเงินน้อยกว่าอัตราค่าใช้จ่าย");
                return;
            }

            RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
            RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
            RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
            RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");
            Label lblTotalAmount = (Label)item.FindControl("lblTotalAmount");
            double dTotalAmount = dAmount
                * (txtMan.Value != null ? txtMan.Value.Value : 1)
                * (txtDay.Value != null ? txtDay.Value.Value : 1)
                * (txtHour.Value != null ? txtHour.Value.Value : 1)
                * (txtMinute.Value != null ? txtMinute.Value.Value : 1);

            lblTotalAmount.Text = dTotalAmount.ToString("#,###.00");
            CalculateSumAmount();
        }

        protected void CalculateSumAmount()
        {
            double dSumAmount = 0;

            foreach (RepeaterItem item in RepeaterExpRate.Items)
            {
                Label lblTotalAmount = (Label)item.FindControl("lblTotalAmount");
                dSumAmount = dSumAmount + (lblTotalAmount.Text.Length > 0 ? Convert.ToDouble(lblTotalAmount.Text) : 0);
            }

            txtAmount.Text = dSumAmount.ToString("#,###.00");
        }

        //protected void txtUnitQtyOper_TextChanged(object sender, EventArgs e)
        //{
        //    CalculatePrice();
        //}

        //protected void txtUnitPriceOper_TextChanged(object sender, EventArgs e)
        //{
        //    CalculatePrice();
        //}

        //protected void CalculatePrice()
        //{
        //    double dPrice = (txtUnitPriceOper.Value != null ? txtUnitPriceOper.Value.Value : 0);
        //    double dQty = (txtUnitQtyOper.Value != null ? txtUnitQtyOper.Value.Value : 0);
        //}

        protected void cmdInsert2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
                return;

            if (!CheckAmount(lblBgmSourceSeq.Text, lblBgmExpGrpSeq.Text, txtAmount.Text))
                return;

            Nullable<int> nBgmProjExpSeq = main.ConvertNullInt(lblBgmProjExpSeq.Text);
            Nullable<int> nBgmProjOperSeq = main.ConvertNullInt(lblBgmProjOperSeq.Text);
            Nullable<double> dAmount = main.ConvertNullDouble(txtAmount.Text);
            Nullable<int> nEmpSeq = main.ConvertNullInt(Session["EmpSeq"]);

            BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense info = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
            info.bgm_proj_oper_seq = nBgmProjOperSeq;
            info.bgm_proj_exp_seq = nBgmProjExpSeq;
            info.bgm_proj_oper_exp_descr = txtBgmProjOperExpDescr.Text;
            info.amount = dAmount;

            if (PanelInv.Visible)
            {
                info.unit_price = txtUnitPriceProj.Value;
                info.unit_qty = main.ConvertNullInt(txtUnitQtyProj.Text);
            }
            else
            {
                info.unit_price = null;
                info.unit_qty = null;
            }

            info.created_by = nEmpSeq;
            info.created_when = DateTime.Today;
            int nBgmProjOperExpSeq = Convert.ToInt32(poexp.Insert(info));
            //Convert.ToInt32(poexp.SelectRecentInsertedRoleSeq());

            if (PanelExpRate.Visible)
            {
                foreach (RepeaterItem item in RepeaterExpRate.Items)
                {
                    BGM_ProjectOperationExpenseRate.M_BGM_ProjectOperationExpenseRate rateInfo = new BGM_ProjectOperationExpenseRate.M_BGM_ProjectOperationExpenseRate();
                    string strTotalAmount = main.WebString(((Label)item.FindControl("lblTotalAmount")).Text);
                    string strBgmProjOperExpRateSeq = main.WebString(((Label)item.FindControl("lblBgmProjOperExpRateSeq")).Text);

                    if (main.ConvertNullDouble(strTotalAmount) > 0)
                    {
                        RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
                        RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
                        RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
                        RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");

                        rateInfo.bgm_proj_oper_exp_seq = nBgmProjOperExpSeq;
                        rateInfo.exp_rate_seq = main.ConvertNullInt(((Label)item.FindControl("lblExpRateSeq")).Text);
                        rateInfo.amount = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtAmount")).Text);

                        if (txtMan.Visible)
                        {
                            rateInfo.man = main.ConvertNullInt(((RadNumericTextBox)item.FindControl("txtMan")).Text);
                        }
                        else
                        {
                            rateInfo.man = null;
                        }

                        if (txtDay.Visible)
                        {
                            rateInfo.day = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtDay")).Text);
                        }
                        else
                        {
                            rateInfo.day = null;
                        }

                        if (txtHour.Visible)
                        {
                            rateInfo.hour = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtHour")).Text);
                        }
                        else
                        {
                            rateInfo.hour = null;
                        }

                        if (txtMinute.Visible)
                        {
                            rateInfo.minute = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtMinte")).Text);
                        }
                        else
                        {
                            rateInfo.minute = null;
                        }

                        if (strBgmProjOperExpRateSeq.Length == 0)
                        {
                            rateInfo.created_by = nEmpSeq;
                            rateInfo.created_when = DateTime.Today;
                            poexprate.Insert(rateInfo);
                        }
                        else
                        {
                            rateInfo.bgm_proj_oper_exp_rate_seq = main.ConvertNullInt(strBgmProjOperExpRateSeq);
                            rateInfo.updated_by = nEmpSeq;
                            rateInfo.updated_when = DateTime.Today;
                            poexprate.Update(rateInfo);
                        }
                    }
                    else if (strBgmProjOperExpRateSeq.Length > 0)
                    {
                        rateInfo.bgm_proj_oper_exp_rate_seq = main.ConvertNullInt(strBgmProjOperExpRateSeq);
                        rateInfo.updated_by = nEmpSeq;
                        rateInfo.updated_when = DateTime.Today;
                        poexprate.Delete(rateInfo);
                    }
                }
            }

            ClearControl2();
            PanelProjOperExp.Visible = false;
            PanelOpacity.Visible = false;
            LoadGrdBgmProjectOperationExpense();
            LoadRepeater4();
            SetProgress(lblBgmProjOperSeq.Text);
        }

        protected void cmdUpdate2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
                return;

            if (!CheckAmount(lblBgmSourceSeq.Text, lblBgmExpGrpSeq.Text, txtAmount.Text))
                return;

            int nBgmProjOperExpSeq = Convert.ToInt32(lblBgmProjOperExpSeq.Text);
            Nullable<int> nBgmProjExpSeq = main.ConvertNullInt(lblBgmProjExpSeq.Text);
            Nullable<int> nBgmProjOperSeq = main.ConvertNullInt(lblBgmProjOperSeq.Text);
            Nullable<double> dAmount = main.ConvertNullDouble(txtAmount.Text);
            Nullable<int> nEmpSeq = main.ConvertNullInt(Session["EmpSeq"]);

            BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense info = new BGM_ProjectOperationExpense.M_BGM_ProjectOperationExpense();
            info.bgm_proj_oper_exp_seq = nBgmProjOperExpSeq;
            info.bgm_proj_oper_seq = nBgmProjOperSeq;
            info.bgm_proj_oper_exp_descr = txtBgmProjOperExpDescr.Text;
            info.bgm_proj_exp_seq = nBgmProjExpSeq;
            info.amount = dAmount;
            //info.currency_seq = main.GetSystemControls().default_currency_seq;
            //info.exchange_rate = 1;
            //info.bath_amount = dAmount;

            if (PanelInv.Visible)
            {
                info.unit_price = txtUnitPriceProj.Value;
                info.unit_qty = main.ConvertNullInt(txtUnitQtyProj.Text);
            }
            else
            {
                info.unit_price = null;
                info.unit_qty = null;
            }

            info.updated_by = nEmpSeq;
            info.updated_when = DateTime.Today;

            poexp.Update(info);

            if (PanelExpRate.Visible)
            {
                foreach (RepeaterItem item in RepeaterExpRate.Items)
                {
                    BGM_ProjectOperationExpenseRate.M_BGM_ProjectOperationExpenseRate rateInfo = new BGM_ProjectOperationExpenseRate.M_BGM_ProjectOperationExpenseRate();
                    string strTotalAmount = main.WebString(((Label)item.FindControl("lblTotalAmount")).Text);
                    string strBgmProjOperExpRateSeq = main.WebString(((Label)item.FindControl("lblBgmProjOperExpRateSeq")).Text);

                    if (main.ConvertNullDouble(strTotalAmount) > 0)
                    {
                        RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
                        RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
                        RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
                        RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");

                        rateInfo.bgm_proj_oper_exp_seq = nBgmProjOperExpSeq;
                        rateInfo.exp_rate_seq = main.ConvertNullInt(((Label)item.FindControl("lblExpRateSeq")).Text);
                        rateInfo.amount = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtAmount")).Text);

                        if (txtMan.Visible)
                        {
                            rateInfo.man = main.ConvertNullInt(((RadNumericTextBox)item.FindControl("txtMan")).Text);
                        }
                        else
                        {
                            rateInfo.man = null;
                        }

                        if (txtDay.Visible)
                        {
                            rateInfo.day = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtDay")).Text);
                        }
                        else
                        {
                            rateInfo.day = null;
                        }

                        if (txtHour.Visible)
                        {
                            rateInfo.hour = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtHour")).Text);
                        }
                        else
                        {
                            rateInfo.hour = null;
                        }

                        if (txtMinute.Visible)
                        {
                            rateInfo.minute = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtMinte")).Text);
                        }
                        else
                        {
                            rateInfo.minute = null;
                        }

                        if (strBgmProjOperExpRateSeq.Length == 0)
                        {
                            rateInfo.created_by = nEmpSeq;
                            rateInfo.created_when = DateTime.Today;
                            poexprate.Insert(rateInfo);
                        }
                        else
                        {
                            rateInfo.bgm_proj_oper_exp_rate_seq = main.ConvertNullInt(strBgmProjOperExpRateSeq);
                            rateInfo.updated_by = nEmpSeq;
                            rateInfo.updated_when = DateTime.Today;
                            poexprate.Update(rateInfo);
                        }
                    }
                    else if (strBgmProjOperExpRateSeq.Length > 0)
                    {
                        rateInfo.bgm_proj_oper_exp_rate_seq = main.ConvertNullInt(strBgmProjOperExpRateSeq);
                        rateInfo.updated_by = nEmpSeq;
                        rateInfo.updated_when = DateTime.Today;
                        poexprate.Delete(rateInfo);
                    }
                }
            }

            ClearControl2();
            PanelProjOperExp.Visible = false;
            PanelOpacity.Visible = false;
            LoadGrdBgmProjectOperationExpense();
            LoadRepeater4();
        }

        protected void cmdCancel2_Click(object sender, EventArgs e)
        {
            ClearControl2();
            PanelProjOperExp.Visible = false;
            PanelOpacity.Visible = false;
        }

        protected void LoadRepeater1()
        {
            string strBgmProjSeq = ddlBgmProjSeq.SelectedValue;

            if (strBgmProjSeq.Length == 0)
                strBgmProjSeq = "-1";

            IList<BGM_MAS_Option.M_BGM_MAS_Option> infoList = op.GetListFromBgmProjSeq("3", strBgmProjSeq);// HardCode
            Repeater1.DataSource = infoList;
            Repeater1.DataBind();
        }

        protected void LoadRepeater4()
        {
            double dSumRemainAmount = 0;
            double dSumProjAmount = 0;
            string strBgmProjSeq = ddlBgmProjSeq.SelectedValue;
            string strBgmProjOperSeq = lblBgmProjOperSeq.Text;

            IList<BGM_Project.M_BGM_Project> infoList = pj.GetBudget(strBgmProjSeq, null, strBgmProjOperSeq);
            Repeater4.DataSource = infoList;
            Repeater4.DataBind();

            for (int i = 0; i < infoList.Count; i++)
            {
                dSumRemainAmount = dSumRemainAmount + infoList[i].remain_amount.Value;
                dSumProjAmount = dSumProjAmount + infoList[i].project_amount.Value;
            }

            lblSumRemainAmount.Text = dSumRemainAmount.ToString("#,###.00");
            lblSumProjectAmount.Text = dSumProjAmount.ToString("#,###.00");
        }

        protected void LoadRepeaterPerson()
        {
            string strBgmProjOperSeq = lblBgmProjOperSeq.Text;

            IList<BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson> infoList = poper.GetFull(strBgmProjOperSeq);
            RepeaterPerson.DataSource = infoList;
            RepeaterPerson.DataBind();
        }

        protected bool CheckData1()
        {
            bool bOK = true;
            string strError = "";
            string strBgmYear = txtBgmYear.Text;
            string strBgmProjSeq = ddlBgmProjSeq.SelectedValue;
            string strBgmProjName = txtBgmProjOperName.Text;
            Nullable<DateTime> dStartDate = dpStartDate.GetDateValue();
            Nullable<DateTime> dEndDate = dpEndDate.GetDateValue();

            if (strBgmYear.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ปีงบประมาณ");
            }
            else if (strBgmProjSeq.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("งาน/โครงการ");
            }
            else if (strBgmProjName.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ชื่อรายการ");
            }
            else if (dStartDate != null && dEndDate != null)
            {
                if (dStartDate.Value > dEndDate.Value)
                {
                    bOK = false;
                    strError = "วันที่เริ่มต้นไม่สัมพันธ์กับวันที่สิ้นสุด";
                }
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckData2()
        {
            bool bOK = true;
            string strError = "";
            string strAmount = txtAmount.Text;

            if (strAmount.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("จำนวนเงินที่ขอ");
            }
            else if (chkManual.Visible && chkManual.Checked && txtBgmProjOperExpDescr.Text.Trim().Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("กรุณากรอกรายละเอียดของจำนวนเงินที่ขอด้วย");
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckData3()
        {
            bool bOK = true;
            string strError = "";
            string strEmpSeq = ddlEmpSeq.SelectedValue;

            if (strEmpSeq.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ชื่อผู้ดำเนินโครงการ");
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckAmount(string strBgmSourceSeq, string strBgmExpGrpSeq, string strAmount)
        {
            bool bOK = true;

            for (int i = 0; i < Repeater4.Items.Count; i++)
            {
                HtmlInputHidden hBgmSourceSeq = (HtmlInputHidden)Repeater4.Items[i].FindControl("hBgmSourceSeq");
                HtmlInputHidden hBgmExpGrpSeq = (HtmlInputHidden)Repeater4.Items[i].FindControl("hBgmExpGrpSeq");

                if (hBgmSourceSeq != null || hBgmExpGrpSeq != null)
                {
                    if (hBgmSourceSeq.Value == strBgmSourceSeq && hBgmExpGrpSeq.Value == strBgmExpGrpSeq)
                    {
                        Label lblRemainAmount = (Label)Repeater4.Items[i].FindControl("lblRemainAmount");
                        Label lblProjectAmount = (Label)Repeater4.Items[i].FindControl("lblProjectAmount");
                        double dRemainAmount = (main.WebString(lblRemainAmount.Text).Length > 0 ? Convert.ToDouble(lblRemainAmount.Text) : 0);
                        double dProjectAmount = (main.WebString(lblProjectAmount.Text).Length > 0 ? Convert.ToDouble(lblProjectAmount.Text) : 0);
                        double dAmount = (strAmount.Length > 0 ? Convert.ToDouble(strAmount) : 0);

                        if ((dProjectAmount - Convert.ToDouble(ViewState["Amount"])) + dAmount > dRemainAmount)
                        {
                            bOK = false;
                            main.MessageAlert(Page, "จำนวนเงินเกินงบประมาณที่ได้รับ");
                        }
                    }
                }
            }

            return bOK;
        }

        protected void Insert1()
        {
            try
            {
                if (!CheckData1())
                    return;

                string strBgmProjOperSeq;
                string strJobsiteSeq = lblWorkingJobSiteSeq.Text;
                string strBgmProjOperDate = lblBgmProjOperDate.Text;
                string strBgmYear = txtBgmYear.Text;
                string strBgmProjSeq = ddlBgmProjSeq.SelectedValue;
                string strStartDate = dpStartDate.GetStringValue();
                string strEndDate = dpEndDate.GetStringValue();
                string strBgmProjOperName = txtBgmProjOperName.Text;
                string strAttendCount = txtAttendCount.Text;
                string strEmpSeq = Session["EmpSeq"].ToString();

                string strIsUse = "1";
                string strUserID = Session["EmpSeq"].ToString();
                DateTime dtNow = DateTime.Now;
                //BGM_ProjectOperation.M_BGM_ProjectOperation info = new BGM_ProjectOperation.M_BGM_ProjectOperation();
                KPIS.GERP.ESS.DAL.M_BGM_ProjectOperation info = new KPIS.GERP.ESS.DAL.M_BGM_ProjectOperation();

                info.bgm_proj_oper_date = main.ConvertNullDateTime(strBgmProjOperDate);
                info.start_date = main.ConvertNullDateTime(strStartDate);
                info.bgm_proj_oper_name = strBgmProjOperName;
                info.end_date = main.ConvertNullDateTime(strEndDate);
                info.bgm_year = main.ConvertNullInt(strBgmYear);
                info.bgm_proj_seq = main.ConvertNullInt(strBgmProjSeq);
                info.emp_seq = main.ConvertNullInt(strEmpSeq);
                info.job_site_seq = main.ConvertNullInt(strJobsiteSeq);
                info.is_use = strIsUse;
                info.attend_count = main.ConvertNullInt(strAttendCount);

                info.created_by = main.ConvertNullInt(strUserID);
                info.created_when = dtNow;

                strBgmProjOperSeq = new D_BgmProjectOperation().Insert(info);
                lblBgmProjOperSeq.Text = strBgmProjOperSeq;
                lblBgmProjOperCode.Text = po.GetInfo(strBgmProjOperSeq).bgm_proj_oper_code;
                cmdProgress2_Click(null, null);
                SetProgress(strBgmProjOperSeq);
                Session["ReportSeq"] = strBgmProjOperSeq;
                main.MessageAlert(Page, "รหัสรายการคือ " + lblBgmProjOperCode.Text);
            }
            catch (Exception exception)
            {

                main.MessageAlert(Page, exception.Message);
            }
        }

        protected void Update1()
        {
            if (!CheckData1())
                return;

            string strBgmProjOperSeq = lblBgmProjOperSeq.Text;
            string strJobsiteSeq = lblWorkingJobSiteSeq.Text;
            string strBgmProjOperDate = lblBgmProjOperDate.Text;
            string strBgmYear = txtBgmYear.Text;
            string strBgmProjSeq = ddlBgmProjSeq.SelectedValue;
            string strStartDate = dpStartDate.GetStringValue();
            string strEndDate = dpEndDate.GetStringValue();
            string strBgmProjOperName = txtBgmProjOperName.Text;
            string strAttendCount = txtAttendCount.Text;
            string strBgmProjOperCode = lblBgmProjOperCode.Text;
            string strEmpSeq = Session["EmpSeq"].ToString();

            string strIsUse = "1";
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperation.M_BGM_ProjectOperation info = new BGM_ProjectOperation.M_BGM_ProjectOperation();

            info.bgm_proj_oper_seq = Convert.ToInt32(strBgmProjOperSeq);
            info.bgm_proj_oper_code = strBgmProjOperCode;
            info.bgm_proj_oper_date = main.ConvertNullDateTime(strBgmProjOperDate);
            info.start_date = main.ConvertNullDateTime(strStartDate);
            info.bgm_proj_oper_name = strBgmProjOperName;
            info.end_date = main.ConvertNullDateTime(strEndDate);
            info.bgm_year = main.ConvertNullInt(strBgmYear);
            info.bgm_proj_seq = main.ConvertNullInt(strBgmProjSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.job_site_seq = main.ConvertNullInt(strJobsiteSeq);
            info.is_use = strIsUse;
            info.attend_count = main.ConvertNullInt(strAttendCount);

            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = dtNow;

            po.Update(info);
            cmdProgress2_Click(null, null);
        }

        protected void Delete1()
        {
            if (GrdViewAll.SelectedItems.Count > 0)
            {
                string strStatus = ((GridDataItem)GrdViewAll.SelectedItems[0])["record_status"].Text;
                if (strStatus == "W" || strStatus == "R")
                {
                    string strBgmProjOperSeq = ((GridDataItem)GrdViewAll.SelectedItems[0])["bgm_proj_oper_seq"].Text;
                    string strUserID = Session["EmpSeq"].ToString();
                    DateTime dtNow = DateTime.Now;

                    BGM_ProjectOperation.M_BGM_ProjectOperation ProjectInfo = new BGM_ProjectOperation.M_BGM_ProjectOperation();
                    ProjectInfo.bgm_proj_oper_seq = Convert.ToInt32(strBgmProjOperSeq);
                    ProjectInfo.updated_by = main.ConvertNullInt(strUserID);
                    ProjectInfo.updated_when = dtNow;

                    po.Delete(ProjectInfo);
                    LoadGrdViewAll();
                    SetControl("ViewAll");
                }
                else
                {
                    main.MessageAlert(Page, "ไม่สามารถลบรายการได้");
                }
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกรายการที่ต้องการลบ");
            }
        }

        protected void Insert3()
        {
            if (!CheckData3())
                return;

            string strBgmProjOperSeq = lblBgmProjOperSeq.Text;
            string strEmpSeq = ddlEmpSeq.SelectedValue;

            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson info = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();

            info.bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjOperSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);

            info.created_by = main.ConvertNullInt(strUserID);
            info.created_when = dtNow;

            poper.Insert(info);
            LoadRepeaterPerson();
            ClearControl3();
            SetProgress(strBgmProjOperSeq);
            cmdDelete1.Visible = false;
        }

        protected void Update3()
        {
            if (!CheckData3())
                return;

            string strBgmProjOperPerSeq = lblBgmProjOperPerSeq.Text;
            string strBgmProjOperSeq = lblBgmProjOperSeq.Text;
            string strEmpSeq = ddlEmpSeq.SelectedValue;

            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson info = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();

            info.bgm_proj_oper_per_seq = Convert.ToInt32(strBgmProjOperPerSeq);
            info.bgm_proj_oper_seq = main.ConvertNullInt(strBgmProjOperSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);

            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = dtNow;

            poper.Update(info);
            LoadRepeaterPerson();
            ClearControl3();
            cmdDelete1.Visible = false;
        }

        protected void Delete3()
        {
            string strBgmProjOperPerSeq = lblBgmProjOperPerSeq.Text;

            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson info = new BGM_ProjectOperationPerson.M_BGM_ProjectOperationPerson();

            info.bgm_proj_oper_per_seq = Convert.ToInt32(strBgmProjOperPerSeq);

            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = dtNow;

            poper.Delete(info);
            LoadRepeaterPerson();
            ClearControl3();
            SetProgress(lblBgmProjOperSeq.Text);
            cmdDelete1.Visible = false;
        }

        protected void cmdExportToMsWord_Click(object sender, EventArgs e)
        {
            ExportToMsWord();
        }

        protected void ExportToMsWord()
        {
            if (!PanelSummary.Visible)
            {
                main.MessageAlert(Page, "รองรับเฉพาะหน้าจอ [สรุปรายการ] เท่านั้น");
                return;
            }

            string strFileName = "Export-.doc";
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "application/vnd.ms-word";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
            //EnableViewState = false;
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            PanelSummary.RenderControl(oHtmlTextWriter);
            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
        }

        //==================== MessageSend ========================

        protected void LoadApprover()
        {
            // Edit by Aek 2014-07-29
            // Calculate base on to_emp_seq field in table message_send, not login session 
            DataTable dtb = send.GetCurrentApprover(SsMng.EmpSeq, null, "BGM_PROJECT_OPERATION", 1);
            ddlApprover.Enabled = true;

            if (dtb != null)
            {
                if (dtb.Rows.Count > 0)
                {
                    lblApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                    SetEmpInfo(dtb.Rows[0]["emp_seq"].ToString(), dtb.Rows[0]["pos_seq"].ToString());
                    ddlApprover.Enabled = false;
                }
            }
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlApprover.DataBind();
        }

        protected void ddlEmpSeq_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlEmpSeq.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlEmpSeq.Items.Count);
        }

        protected void ddlEmpSeq_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlEmpSeq.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", "");
            ddlEmpSeq.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            if (lblApproveEmpSeq.Text.Length == 0)
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                //RadAjaxManager1.Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                return;
            }

            try
            {
                string strBgmProjOperSeq = lblBgmProjOperSeq.Text;
                ESS.MODEL.M_MessageSend info = new ESS.MODEL.M_MessageSend();
                info.send_date = DateTime.Today;
                info.ref_seq = main.ConvertNullInt(strBgmProjOperSeq);
                info.ref_type = "bgm_project_operation";
                info.ref_no = lblFinBgmProjOperCode.Text;
                info.send_text = "ส่งคำขออนุมัติดำเนินงาน : " + lblFinBgmProjOperName.Text;
                info.from_emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.to_emp_seq = main.ConvertNullInt(lblApproveEmpSeq.Text);

                info.from_pos_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.to_pos_seq = main.ConvertNullInt(lblApprovePosSeq.Text);
                info.wod_emp_seq = null;

                info.from_send_seq = null;
                info.remarks = null;
                info.message_status = "0";
                info.approve_path_seq = main.ConvertNullInt(lblApprovePathSeq.Text);
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Now;
                send.Insert(info);

                BGM_ProjectOperation.M_BGM_ProjectOperation info2 = new BGM_ProjectOperation.M_BGM_ProjectOperation();
                info2.bgm_proj_oper_seq = Convert.ToInt32(strBgmProjOperSeq);
                info2.record_status = "P";
                info2.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info2.updated_when = DateTime.Now;
                po.ChangeStatus(info2);
                cmdSummary_Click(null, null);
                //lblRecordStatus.Text = "P";
                //lblFinRecordStatus.Text = "P";
                //lblFinRecordStatusName.Text = "รอการอนุมัติ";
                //cmdSendMessage1.Visible = false;
                //lblFinRecordStatusName.ForeColor = System.Drawing.Color.Blue;
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("บันทึกเรียบร้อยแล้ว");
                //RadAjaxManager1.Alert("บันทึกเรียบร้อยแล้ว");

                PanelMessageSend.Visible = false;
                //ScriptManager.RegisterClientScriptBlock(
                //    this.Page,
                //    this.GetType(),
                //    "WebUserControlSript",
                //    "CloseActiveToolTip()",
                //    true);
            }
            catch
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("เกิดข้อผิดพลาดในการบันทึกข้อมูล");
                //RadAjaxManager1.Alert("เกิดข้อผิดพลาดในการบันทึกข้อมูล");
            }
        }

        protected void SetEmpInfo(string strEmpSeq, string strPosSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                DataTable dtb = emplist.GetInfo(Convert.ToInt32(strEmpSeq));

                lblApproveEmpSeq.Text = dtb.Rows[0]["sequence"].ToString();
                lblApprovePosSeq.Text = string.IsNullOrEmpty(strPosSeq) ? dtb.Rows[0]["t_pos_seq"].ToString() : strPosSeq;
                //lblApproverName.Text = dtb.Rows[0]["full_name"].ToString();
                lblPosName.Text = dtb.Rows[0]["pos_name"].ToString() + (strPosSeq != dtb.Rows[0]["t_pos_seq"].ToString() ? " (รักษาการณ์แทน " + GetPositionName(strPosSeq) + ")" : "");
                lblClassName.Text = dtb.Rows[0]["class_name"].ToString();
                lblExecPosName.Text = dtb.Rows[0]["exec_pos_name"].ToString();
                lblJobsiteName.Text = dtb.Rows[0]["job_site_name"].ToString();
                ddlApprover.Text = dtb.Rows[0]["full_name"].ToString();
            }
        }

        protected string GetPositionName(string strPosSeq)
        {
            dbManager.Open();
            DataTable dtb = null;

            try
            {
                dbManager.CreateParameters(1);
                dbManager.AddParameters(0, "@pos_seq", strPosSeq);

                string strSQL = "SELECT pos_name FROM hrm_mp_positions where pos_seq = @pos_seq";

                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                if (dtb.Rows.Count > 0)
                {
                    return dtb.Rows[0][0].ToString();
                }

                return "";
            }
            catch
            {
                return "";
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        protected void OnAjaxUpdate(object sender, ToolTipUpdateEventArgs args)
        {
            PanelMessageSend.Visible = true;
            args.UpdatePanel.ContentTemplateContainer.Controls.Add(PanelMessageSend);
        }

        protected void GrdViewAll_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                string strRecordStatus = ((GridDataItem)e.Item)["record_status"].Text;
                TableCell cell = ((GridDataItem)e.Item)["record_status_name"];

                switch (strRecordStatus)
                {
                    case "W" :
                    default :
                        cell.ForeColor = System.Drawing.Color.Red;
                        break;
                    case "P" :
                        cell.ForeColor = System.Drawing.Color.Blue;
                        break;
                    case "A" :
                        cell.ForeColor = System.Drawing.Color.Green;
                        break;
                }
            }
        }

        protected void GrdViewAll_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Filter" || e.CommandName == "Sort" || e.CommandName == "Page")
            {
                LoadGrdViewAll();
            }
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetEmpInfo(ddlApprover.SelectedValue, null);
        }

        protected void cmdSendMessage1_Click(object sender, EventArgs e)
        {
            PanelMessageSend.Visible = true;
            ddlApprover.SelectedIndex = -1;
            lblClassName.Text = "";
            lblExecPosName.Text = "";
            lblJobsiteName.Text = "";
            lblPosName.Text = "";
            lblApproveEmpSeq.Text = "";
            lblApprovePosSeq.Text = "";

            //if (lblFinRecordStatus.Text == "R")
            //{
            //    var model = send.GetLatestMessageStatus(lblBgmProjOperSeq.Text, "bgm_project_operation");
            //    lblApprovePathSeq.Text = model.approve_path_seq.ToString();
            //    ddlApprover.SelectedValue = model.to_emp_seq.ToString();
            //    ddlApprover_SelectedIndexChanged(null, null);
            //}
            //else
            //{
                LoadApprover();
            //}
        }

        protected void grdBgmProjectOperationExpense_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                bool bCanEdit = (lblRecordStatus.Text != "A" && lblRecordStatus.Text != "D");
                ((LinkButton)e.Item.FindControl("cmdAddExpense")).Enabled = bCanEdit;
            }
        }

        protected void lblRemainAmount_Click(object sender, EventArgs e)
        {
            txtAmount.Text = lblRemainAmount.Text;
        }

        protected void txtUnitQtyProj_TextChanged(object sender, EventArgs e)
        {
            CalculateAmount();
        }

        protected void txtUnitPriceProj_TextChanged(object sender, EventArgs e)
        {
            CalculateAmount();
        }

        protected void CalculateAmount()
        {
            double dUnitQtyProj = (double.TryParse(txtUnitQtyProj.Text, out dUnitQtyProj) ? 
                (txtUnitQtyProj.Value.Value >= 0 ? txtUnitQtyProj.Value.Value : 0) : 0);
            double dUnitPriceProj = (double.TryParse(txtUnitPriceProj.Text, out dUnitPriceProj) ?
                (txtUnitPriceProj.Value.Value >= 0 ? txtUnitPriceProj.Value.Value : 0) : 0);

            txtAmount.Text = (dUnitQtyProj * dUnitPriceProj).ToString("#,###.00");
        }

        protected void chkManual_CheckedChanged(object sender, EventArgs e)
        {
            txtAmount.Enabled = chkManual.Checked;
        }

        protected void cmdCancelMessage_Click(object sender, EventArgs e)
        {
            var message = send.GetInfoFromRefSeq(lblBgmProjOperSeq.Text, "bgm_project_operation");
            message.updated_by = SsMng.EmpSeqI;
            message.updated_when = DateTime.Now;
            send.Delete(message);

            var project = po.GetInfo(lblBgmProjOperSeq.Text);
            project.record_status = "W";
            project.updated_by = SsMng.EmpSeqI;
            project.updated_when = DateTime.Now;
            po.ChangeStatus(project);

            cmdProgress1_Click(null, null);
        }
    }
}
